package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.utils.ThrowUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.ICheckInService;
import com.zzyl.nursing.utils.CodeGenerator;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author ruoyi
 * @date 2025-10-17
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    private final ElderMapper elderMapper;
    private final BedMapper bedMapper;
    private final CheckInMapper checkInMapper;
    private final CheckInConfigMapper checkInConfigMapper;
    private final ContractMapper contractMapper;

    /**
     * 查询【请填写功能名称】
     *
     * @param id 【请填写功能名称】主键
     * @return 【请填写功能名称】
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询【请填写功能名称】列表
     *
     * @param checkIn 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return baseMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增【请填写功能名称】
     *
     * @param checkIn 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改【请填写功能名称】
     *
     * @param checkIn 【请填写功能名称】
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {

        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除【请填写功能名称】
     *
     * @param ids 需要删除的【请填写功能名称】主键
     * @return 结果
     */

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除【请填写功能名称】信息
     *
     * @param id 【请填写功能名称】主键
     * @return 结果
     */

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void checkInApply(CheckInApplyDto checkInApplyDto) {
        //进行入住申请
        // 判断老人是否已经入住
        CheckInElderDto checkInElderDto = checkInApplyDto.getCheckInElderDto();
        CheckInConfigDto checkInConfigDto = checkInApplyDto.getCheckInConfigDto();

        // 通过身份证号查询老人
        Elder elder = elderMapper.selectOne(Wrappers.lambdaQuery(Elder.class).eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()));
        ThrowUtils.throwIf(elder != null, "该身份证号的老人已经入住了" );
        // 更新床位的状态为已入住
        Bed bed = bedMapper.selectOne(Wrappers.lambdaQuery(Bed.class).eq(Bed::getId, checkInConfigDto.getBedId()));
        ThrowUtils.throwIf(bed == null, "床位不存在" );
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        // 保存或更新老人数据
        elder = insertOrUpdate(bed, checkInApplyDto.getCheckInElderDto());
        // 生成合同编号
        String contractNo = "HT" + CodeGenerator.generateContractNumber();
        // 新增签约办理
        insertContract(contractNo, elder, checkInApplyDto);
        // 新增入住信息
        CheckIn checkIn = insertCheckIn(elder, checkInApplyDto);

        // 新增入住配置信息
        insertCheckInConfig(checkIn.getId(), checkInApplyDto);
    }


    /**
     * 新增入住配置
     *
     * @param checkInId       入住信息ID
     * @param checkInApplyDto 入住申请信息
     */
    private void insertCheckInConfig(Long checkInId, CheckInApplyDto checkInApplyDto) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInConfigDto(), checkInConfig);
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住信息
     *
     * @param elder           老人信息
     * @param checkInApplyDto 入住申请信息
     */
    private CheckIn insertCheckIn(Elder elder, CheckInApplyDto checkInApplyDto) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(checkInApplyDto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }


    /**
     * 新增合同
     *
     * @param contractNo      合同编号
     * @param elder           老人信息
     * @param checkInApplyDto 入住申请信息
     */
    private void insertContract(String contractNo, Elder elder, CheckInApplyDto checkInApplyDto) {
        Contract contract = new Contract();
        // 属性拷贝
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime checkInStartTime = checkInApplyDto.getCheckInConfigDto().getStartDate();
        LocalDateTime checkInEndTime = checkInApplyDto.getCheckInConfigDto().getEndDate();
        Integer status = checkInStartTime.isBefore(LocalDateTime.now()) ? 0 : 1;
        contract.setStatus(status);
        contract.setStartDate(checkInStartTime);
        contract.setEndDate(checkInEndTime);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人
     *
     * @param bed             床位信息
     * @param checkInElderDto 入住老人信息
     * @return 新增或更新老人信息
     */
    private Elder insertOrUpdate(Bed bed, CheckInElderDto checkInElderDto) {
        // 准备老人数据
        Elder elder = new Elder();
        // 属性拷贝
        BeanUtils.copyProperties(checkInElderDto, elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        // 查询老人信息，（身份证号、状态不为1）ne：不等于
        Elder elderDb = elderMapper.selectOne(Wrappers.lambdaQuery(Elder.class).eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo()).ne(Elder::getStatus, 1));
        if (ObjectUtils.isNotEmpty(elderDb)) {
            // 修改
            elderMapper.updateById(elder);
        } else {
            // 新增
            elderMapper.insert(elder);
        }
        return elder;
    }

    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo resp = new CheckInDetailVo();
        CheckIn checkIn = baseMapper.selectById(id);
        ThrowUtils.throwIf(checkIn == null, "没有对应的入住信息" );
        //获取老人信息
        Elder elder = elderMapper.selectOne(Wrappers.lambdaQuery(Elder.class).eq(Elder::getId, checkIn.getElderId()));
        ThrowUtils.throwIf(elder == null, "该老人不存在" );
        CheckInElderVo checkInElderVo = BeanUtil.toBean(elder, CheckInElderVo.class);
        //计算老人年龄
        Date birthday = DateUtil.parse(elder.getBirthday());
        checkInElderVo.setAge(DateUtil.age(birthday, new Date()));
        resp.setCheckInElderVo(checkInElderVo);

        //获取家属信息
        resp.setElderFamilyVoList(JSONUtil.toList(checkIn.getRemark(), ElderFamilyVo.class));

        //获取入住配置信息
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.lambdaQuery(CheckInConfig.class).eq(CheckInConfig::getCheckInId, checkIn.getId()));
        ThrowUtils.throwIf(checkInConfig == null, "入住的信息不存在" );
        CheckInConfigVo checkInConfigVo = BeanUtil.toBean(checkInConfig, CheckInConfigVo.class);
        checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        checkInConfigVo.setStartDate(checkIn.getStartDate());
        checkInConfigVo.setEndDate(checkIn.getEndDate());
        resp.setCheckInConfigVo(checkInConfigVo);

        //获取合同信息
        resp.setContract(contractMapper.selectOne(Wrappers.lambdaQuery(Contract.class).eq(Contract::getElderId, elder.getId())));
        return resp;

    }

}

